// subPages/communityService/upLoadGoods/upLoadGoods.js
const app = getApp();
var util = require('../../../utils/util');
Page({

  /**
   * 页面的初始数据
   */
  data: {
      themeColor:app.globalData.themeColor,
      evalList: [{ tempFilePaths: [], imgList: [] }],
      fmList:[{ tempFilePaths: [], imgList: [] }],
      array:['请选择商品类型','1','2','3'],
      index:0,
      goodsInfoList:[
          {
              key:'商品名称',
              placeholder:'请输入商品名称',
              type:'text',
              max:-1,
              val:'',
              input:'g_name'
          },
          {
              key:'商品价格',
              placeholder:'请输入商品价格(元)',
              type:'digit',
              max:-1,
              val:'',
              input:'g_price'
          },
          {
              key:'联系方式',
              placeholder:'请输入联系方式',
              type:'number',
              max:11,
              val:'',
              input:'g_contact'
          }
      ]
  },
    bindPickerChange(e) {
      let _this = this;
        let idIndex = e.detail.value-1;
        if(idIndex>=0){
            this.setData({
                goods_class:_this.data.goodsClass[idIndex].id
            })
        }else{
            util.showToast('请选择您的商品种类','none',1000);
            this.setData({
                goods_class:null
            })
        }
        this.setData({
            index: e.detail.value
        })
    },
    catchVal(e){
        let that = this;
        var index = e.currentTarget.dataset.index;
        var goodsName,goodsPrice,userName,contactWay,address;
        var goodsInfoList = that.data.goodsInfoList;
        goodsInfoList[index].val = e.detail.value;
        that.setData({
            goodsInfoList:goodsInfoList
        })
    },
    //添加图片
    joinFmPicture:function(e){
        var index = e.currentTarget.dataset.index;
        var fmList = this.data.fmList;
        var that = this;
        var imgNumber = fmList[index].tempFilePaths;
        if (imgNumber.length >= 1) {
            util.showModal('提示','最多上传一张封面图片')
            return;
        }
        wx.showActionSheet({
            itemList: ["从相册中选择", "拍照"],
            itemColor: "#f7982a",
            success: function (res) {
                if (!res.cancel) {
                    if (res.tapIndex == 0) {
                        that.chooseFmWxImage("album", imgNumber);
                    } else if (res.tapIndex == 1) {
                        that.chooseFmWxImage("camera", imgNumber);
                    }
                }
            }
        })
    },
    joinPicture: function (e) {
        var index = e.currentTarget.dataset.index;
        var evalList = this.data.evalList;
        evalList[index].tempFilePaths = [];
        var that = this;
        var imgNumber = evalList[index].tempFilePaths;
        if (imgNumber.length >= 15) {
            util.showModal('提示','最多上传十五张图片')
            return;
        }
        wx.showActionSheet({
            itemList: ["从相册中选择", "拍照"],
            itemColor: "#f7982a",
            success: function (res) {
                if (!res.cancel) {
                    if (res.tapIndex == 0) {
                        that.chooseWxImage("album", imgNumber);
                    } else if (res.tapIndex == 1) {
                        that.chooseWxImage("camera", imgNumber);
                    }
                }
            }
        })
    },

    //选择图片
    chooseFmWxImage: function (type, list) {
        var img = list;
        var len = img.length;
        var that = this;
        var fmList = this.data.fmList;
        wx.chooseImage({
            count: 1,
            sizeType: ["original", "compressed"],
            sourceType: [type],
            success: function (res) {
                var addImg = res.tempFilePaths;
                var addLen = addImg.length;
                if ((len + addLen) > 3) {
                    for (var i = 0; i < (addLen - len); i++) {
                        var str = {};
                        str.pic = addImg[i];
                        img.push(str);
                    }
                } else {
                    for (var j = 0; j < addLen; j++) {
                        var str = {};
                        str.pic = addImg[j];
                        img.push(str);
                    }
                }
                that.setData({
                    fmList: fmList
                })
                that.uploadFm(img);
            },
        })
    },
    chooseWxImage: function (type, list) {
        var img = list;
        var len = img.length;
        var that = this;
        var evalList = this.data.evalList;
        wx.chooseImage({
            count: 9,
            sizeType: ["original", "compressed"],
            sourceType: [type],
            success: function (res) {
                var addImg = res.tempFilePaths;
                var addLen = addImg.length;
                if ((len + addLen) > 15) {
                    for (var i = 0; i < (addLen - len); i++) {
                        var str = {};
                        str.pic = addImg[i];
                        img.push(str);
                    }
                } else {
                    for (var j = 0; j < addLen; j++) {
                        var str = {};
                        str.pic = addImg[j];
                        img.push(str);
                    }
                }
                that.setData({
                    evalList: evalList
                })
                that.upload(img);
            },
        })
    },

    //删除图片
    clearImg: function (e) {
        var that = this;
        var index = e.currentTarget.dataset.index;
        var evalList = this.data.evalList;
        wx.request({
            url: app.globalData.apiUrl +'/Api/First/delete',
            data: {
              file: evalList[0].tempFilePaths[index]
            },
            method: 'get',
            header: {
              'content-type': 'application/json' //默认值
            },
            success: function (res) {
              // console.log(res)
              if(res.data == 1){
                var img = evalList[0].tempFilePaths;
                var img2 = evalList[0].imgList;
                img.splice(index, 1);
                img2.splice(index, 1);
                that.setData({
                    evalList: evalList
                })
              }
            },
            fail: function (res) {
              console.log("失败",res);
            }
        })
    },
    clearFmImg: function (e) {
        var that = this;
        var index = e.currentTarget.dataset.index;
        var fmList = this.data.fmList;
        wx.request({
            url: app.globalData.apiUrl +'/Api/First/delete',
            data: {
              file: fmList[0].tempFilePaths[index]
            },
            method: 'get',
            header: {
              'content-type': 'application/json' //默认值
            },
            success: function (res) {
              // console.log(res)
              if(res.data == 1){
                var img = fmList[0].tempFilePaths;
                var img2 = fmList[0].imgList;
                img.splice(index, 1);
                img2.splice(index, 1);
                that.setData({
                    fmList: fmList
                })
              }
            },
            fail: function (res) {
              console.log("失败",res);
            }
        })
    },

    //多张图片上传
    uploadFm: function (path) {
        var that = this;
        var curImgList = [];
        for (var i = 0; i < path.length; i++) {
            wx.showToast({
                icon: "loading",
                title: "正在上传"
            }),
                wx.uploadFile({
                    url: app.globalData.apiUrl + '/upload',//接口处理在下面有写
                    filePath: path[i].pic,
                    name: 'img',
                    header: { "Content-Type": "multipart/form-data" },
                    formData: {
                        douploadpic: '1'
                    },
                    success: function (res) {
                        curImgList.push('https://jzj.freei.cc'+res.data);
                        var fmList = that.data.fmList;
                        fmList[0].imgList = curImgList;
                        that.setData({
                            fmList: fmList
                        })
                    },
                    fail: function (e) {
                        util.showModal('提示','上传失败')
                        return
                    },
                    complete: function () {
                        wx.hideToast();  //隐藏Toast
                    }
                })
        }
    },
    upload: function (path) {
        var that = this;
        // var curImgList = [];
        var curImgList = '';
        for (var i = 0; i < path.length; i++) {
            wx.showToast({
                icon: "loading",
                title: "正在上传"
            }),
                wx.uploadFile({
                    url: app.globalData.apiUrl + '/upload',//接口处理在下面有写
                    filePath: path[i].pic,
                    name: 'img',
                    header: { "Content-Type": "multipart/form-data" },
                    formData: {
                        douploadpic: '1'
                    },
                    success: function (res) {
                        curImgList = 'https://jzj.freei.cc'+res.data;
                        var evalList = that.data.evalList;
                        // evalList[0].imgList = curImgList;
                        evalList[0].imgList.push(curImgList);

                        that.setData({
                            evalList: evalList
                        })
                    },
                    fail: function (e) {
                        util.showModal('提示','上传失败')
                        return
                    },
                    complete: function () {
                        wx.hideToast();  //隐藏Toast
                    }
                })
        }
    },


    //获取输入框信息
    g_name(e){
      var g_name = e.detail.value,
            _this = this;
      _this.setData({
          g_name:g_name
      })

    },
    g_contact(e){
        var g_contact = e.detail.value,
            _this = this;
        _this.setData({
            g_contact:g_contact
        })
    },
    g_price(e){
        var g_price = e.detail.value,
            _this = this;
        _this.setData({
            g_price:g_price
        })
    },
    g_content(e){
        var g_content = e.detail.value,
            _this = this;
        _this.setData({
            g_content:g_content
        })
    },
    submitBtn(){
        var _this = this;
        var g_name = _this.data.g_name;
        var g_price = _this.data.g_price;
        var g_content = _this.data.g_content;
        var g_contact = _this.data.g_contact;
        var g_class = _this.data.goods_class;
        var fmImg = _this.data.fmList[0].imgList[0];
        var g_fmImg = fmImg;
        var g_evalImg = _this.data.evalList[0].imgList;
        var content_img = []
        for(var i in g_evalImg){
            var img = {img:g_evalImg[i]}
            content_img.push(img)
        }
        var pro = {
            user_id:app.globalData.userId,
            class_id:g_class,
            product_name:g_name,
            content_img:content_img,
            head_img:g_fmImg,
            price:g_price,
            community_id: app.globalData.communityId,
            phone:g_contact,
            sub_content:g_content,
            status:0
        }
        if(_this.data.up_type == 2){
            pro.id = _this.data.goods_id
        }
        if(!g_name||!g_content||!g_contact||!g_class||!fmImg||content_img.length==0||!g_price){
            return util.showToast('请完善您的商品信息！','none',3000);
        }
        pro = JSON.stringify(pro)
        util.getAjax(`${app.globalData.apiUrl}/add_old_product`,res=>{
            if(res.data == 1){
                wx.showModal({
                    title:'提示',
                    content:'您已提交商品！请等待审核！',
                    showCancel:false,
                    success(res){
                        if(res.confirm){
                            wx.navigateBack({
                                delta: 1,
                            });//返回上一页面
                        }
                    }
                })
            }
        },{
            pro:pro,
            type:_this.data.up_type
        })
    },
    /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
        this.getGoodsClass();
      this.setData({
          up_type:options.type
      })
      if(options.type == 2){
          var id = options.id;
          this.setData({
              goods_id:options.id
          })
          this.getGoodsInfo(id)
      }
     util.setNavBarTitle('上传商品');

  },
    //获取类别
    getGoodsClass(){
      let _this = this;
      util.getAjax(app.globalData.apiUrl+'/get_old_product_class',res=>{
          var newArray = ['请选择商品类别'];
          for(var i in res.data){
              newArray.push(res.data[i].class_name);
          }
          _this.setData({
              array:newArray,
              goodsClass:res.data
          })
      },{
          community_id:app.globalData.communityId
      })
    },
    clearInput(e){
        let _this = this;
        let index = e.currentTarget.dataset.index;
        let goodsInfoList = _this.data.goodsInfoList;
        goodsInfoList[index].val = '';
        _this.setData({
            goodsInfoList:goodsInfoList
        })

    },

    //获取产品详情
    getGoodsInfo(id){
      let _this = this;
      setTimeout(function(){
          util.getAjax(`${app.globalData.apiUrl}/get_old_product_content`,res=>{
              var goodsClass = _this.data.goodsClass;
              var index = 0;
              for(var i in goodsClass){
                  if(goodsClass[i].id == res.data.class_id){
                      index = ++i
                  }
              }
              var imgs = [];
              for(var j in res.data.content_img){
                  imgs.push(res.data.content_img[j].img)
              }
              _this.setData({
                  g_name:res.data.product_name,
                  g_price:res.data.price,
                  g_contact:res.data.phone,
                  g_content:res.data.sub_content,
                  goods_class:res.data.class_id,
                  goodsInfoList:[
                      {
                          key:'商品名称',
                          placeholder:'请输入商品名称',
                          type:'text',
                          max:-1,
                          val:res.data.product_name,
                          input:'g_name'
                      },
                      {
                          key:'商品价格',
                          placeholder:'请输入商品价格(元)',
                          type:'digit',
                          max:-1,
                          val:res.data.price,
                          input:'g_price'
                      },
                      {
                          key:'联系方式',
                          placeholder:'请输入联系方式',
                          type:'number',
                          max:11,
                          val:res.data.phone,
                          input:'g_contact'
                      }
                  ],
                  contentVal:res.data.sub_content,
                  index:index,
                  evalList: [{ tempFilePaths: [], imgList: imgs }],
                  fmList:[{ tempFilePaths: [], imgList: [res.data.head_img] }],
              })
          },{
              id:id
          })
      },200)

    },







  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
